package org.hairball.util;

import java.io.*;

public class FileUtils {
    public static File writeFile(String filename, String fileContents) {
        File file = new File(filename);
        FileWriter writer = null;

        try {
            try {
                file.createNewFile();
                writer = new FileWriter(file);
                writer.append(fileContents);
            } catch (IOException e) {
                throw new RuntimeException("Unable to create file " + file);
            }
        } finally {
            closeSafely(writer);
        }
        return file;
    }

    public static String readFile(InputStream inputStream) {
        InputStreamReader streamReader = null;
        BufferedReader bufferedReader = null;
        StringBuilder fileContents = new StringBuilder();

        try {
            streamReader = new InputStreamReader(inputStream);
            bufferedReader = new BufferedReader(streamReader);

            String line = bufferedReader.readLine();
            while (line != null) {
                fileContents.append(line).append("\n");
                line = bufferedReader.readLine();
            }
            return fileContents.toString();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            closeSafely(inputStream);
            closeSafely(streamReader);
            closeSafely(bufferedReader);
        }
        return null;
    }

    private static void closeSafely(Reader reader) {
        if (reader != null) {
            try {
                reader.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }

    private static void closeSafely(InputStream inputStream) {
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }

    private static void closeSafely(FileWriter writer) {
        if (writer != null) {
            try {
                writer.close();
            } catch (IOException e) {
                //ignore
            }
        }
    }
}
